<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>关键问题4</title>
</head>
<body>
	<button onclick="demo()">点我发请求（3个请求依次发）</button>
  <script>
    /* 
    	promise如何串连多个异步任务?
					(1)promise的then()返回一个新的promise, 可以看成then()的链式调用
					(2)通过then的链式调用串连多个任务，从而解决“回调地狱”
    */

		function sendAjax(options){
				return new Promise((resolve,reject)=>{
					//获取请求相关的参数
					const {url,data} = options
					//创建xhr
					const xhr = new XMLHttpRequest()
					//绑定监听
					xhr.onreadystatechange = ()=>{
						if(xhr.readyState === 4 ){
							if(xhr.status >= 200 && xhr.status <= 299) resolve(xhr.response)
							else reject(xhr.response)
						}
					}
					//自动解析json
					xhr.responseType = 'json'
					let str = ''
					for (let key in data){
						str += `${key}=${data[key]}&`
					}
					str = str.slice(0,-1)
					//配置请求信息
					xhr.open('GET',url+'?'+str)
					//发送请求
					xhr.send()
				})
			}
		
		function demo(){
			sendAjax({
				url:'https://api.apiopen.top/getJoke',
			})
			.then(
				value => {
					console.log('第1次成功了',value)
					return sendAjax({url:'https://api.apiopen.top/getJoke'})
				},
				reason => {console.log('第1次失败了',reason)}
			)
			.then(
				value => {
					console.log('第2次成功了',value)
					return sendAjax({url:'https://api.apiopen.top/getJoke'})
				},
				reason => {console.log('第2次失败了',reason)}
			)
			.then(
				value => {console.log('第3次成功了',value)},
				reason => {console.log('第3次失败了',reason)}
			)
		}
</script>
</body>
</html>